from django.shortcuts import render

# Create your views here.


 # categories/(?P<category_id>\d+)/skus?page=xxx&page_size=xxx&ordering=xxx
from drf_haystack.viewsets import HaystackViewSet
from rest_framework.filters import OrderingFilter
from rest_framework.generics import ListAPIView, GenericAPIView
from rest_framework.response import Response

from goods.models import SKU, GoodsCategory
from goods.serializers import SKUSerializer, SKUIndexSerializer, ChannelSerializer, CategorySerializer


class SKUListView(ListAPIView):
    """商品列表
    """
    # 指定查询集
    # queryset = SKU.objects.all()

    # 指定序列化器
    serializer_class = SKUSerializer

    # 指定排序过滤
    filter_backends = [OrderingFilter]
    # ordering_fields ： 内部需要填写模型的属性，告诉DRF的排序将来对这几个字段排序
    ordering_fields = ('create_time', 'price', 'sales')

    # 为了使用category_id对要展示的SKU进行过滤。保证展示的sku是指定的分类的sku
    def get_queryset(self):
        # 从视图对象中的kwargs中读取路径参数
        category_id = self.kwargs['category_id']
        return SKU.objects.filter(category_id=category_id, is_launched=True)



class SKUSearchViewSet(HaystackViewSet):
    """
    SKU搜索
    """
    index_models = [SKU]

    serializer_class = SKUIndexSerializer


class CategoryView(GenericAPIView):
    """
    类别
    """
    queryset = GoodsCategory.objects.all()

    def get(self, request, pk=None):
        ret = dict(
            cat1='',
            cat2='',
            cat3=''
        )
        category = self.get_object()
        if category.parent is None:
            # 当前类别为一级类别
            ret['cat1'] = ChannelSerializer(category.goodschannel_set.all()[0]).data
        elif category.goodscategory_set.count() == 0:
            # 当前类别为三级
            ret['cat3'] = CategorySerializer(category).data
            cat2 = category.parent
            ret['cat2'] = CategorySerializer(cat2).data
            ret['cat1'] = ChannelSerializer(cat2.parent.goodschannel_set.all()[0]).data
        else:
            # 当前类别为二级
            ret['cat2'] = CategorySerializer(category).data
            ret['cat1'] = ChannelSerializer(category.parent.goodschannel_set.all()[0]).data

        return Response(ret)